import obspython as obs
import win32gui
import time
import win32process
import psutil
from datetime import datetime

# 场景切换规则（窗口标题关键词 -> OBS 场景名）
SCENE_RULES = {
    "code": "VSCodeScene",
    "chrome": "浏览器Scene",
    "unity": "UnityScene",
    "rider": "RiderScene"
}

# 脚本设置
data = None
last_check_time = 0
TimeInterval = 0.2
BgSceneName = "背景"
is_auto_switch_enabled = True  # 默认开启自动切换

def get_active_window_title():
    """获取当前活动窗口标题（转换为小写）"""
    try:
        hwnd = win32gui.GetForegroundWindow()
        title = win32gui.GetWindowText(hwnd)
        return title.lower()
    except Exception as e:
        print(obs.LOG_WARNING, f"获取窗口标题失败: {e}")
        return ""

def get_active_window_process_name():
    """获取当前激活窗口的程序名称"""
    try:
        hwnd = win32gui.GetForegroundWindow()
        _, pid = win32process.GetWindowThreadProcessId(hwnd)
        process = psutil.Process(pid)
        return process.name().lower()
    except Exception as e:
        print(obs.LOG_WARNING, f"获取窗口程序名称失败: {e}")
        return None

def switch_scene(target_scene_name):
    """切换到指定场景"""
    current_scene_source = None
    target_scene_source = None

    try:
        current_scene_source = obs.obs_frontend_get_current_scene()
        if current_scene_source is None:
            print(obs.LOG_WARNING, "无法获取当前场景")
            return

        current_scene_name = obs.obs_source_get_name(current_scene_source)
        if current_scene_name == target_scene_name:
            return

        target_scene_source = obs.obs_get_source_by_name(target_scene_name)
        if target_scene_source is None:
            print(obs.LOG_WARNING, f"场景 '{target_scene_name}' 不存在")
            return

        obs.script_log(obs.LOG_INFO, f"正在从 {current_scene_name} 切换到场景: {target_scene_name}")
        obs.obs_frontend_set_current_scene(target_scene_source)
    except Exception as e:
        obs.script_log(obs.LOG_ERROR, f"切换场景时发生错误: {e}")
    finally:
        if target_scene_source is not None:
            obs.obs_source_release(target_scene_source)
        if current_scene_source is not None:
            obs.obs_source_release(current_scene_source)

def update_scene_based_on_window():
    """根据活动窗口切换场景"""
    try:
        title = get_active_window_process_name()
        if not title:
            switch_scene(BgSceneName)
            return
        isToggle = False
        for keyword, scene_name in SCENE_RULES.items():
            if keyword in title:
                switch_scene(scene_name)
                isToggle = True
                return
        if not isToggle:
            switch_scene(BgSceneName)
    except Exception as e:
        obs.script_log(obs.LOG_ERROR, f"更新场景时发生错误: {e}")

def script_tick(seconds):
    """OBS 每帧调用的函数"""
    global last_check_time

    if not is_auto_switch_enabled:  # 如果自动切换关闭，则直接返回
        return

    current_time = time.time()
    if current_time - last_check_time >= TimeInterval:
        last_check_time = current_time
        try:
            update_scene_based_on_window()
        except Exception as e:
            obs.script_log(obs.LOG_ERROR, f"脚本运行时发生错误: {e}")

def script_description():
    return '这是一个根据活动窗口自动切换 OBS 场景的脚本\n作者：\t哎呦喂\n版本：\t1.0.0\n联系：\tfengya011@163.com'

def script_properties():
    """为脚本添加属性"""
    props = obs.obs_properties_create()
    obs.obs_properties_add_float(props, "TimeInterval", "时间间隔", 0.01, 10000, 0.01)
    obs.obs_properties_add_bool(props, "is_auto_switch_enabled", "启用自动切换")
    obs.obs_properties_add_button(props, 'test', '测试', test)
    obs.obs_properties_add_button(props, 'ScreenRecording', '时间间隔录制', start_recording)
    return props

def script_load(settings):
    """加载脚本时初始化配置"""
    global TimeInterval, is_auto_switch_enabled
    TimeInterval = obs.obs_data_get_double(settings, "TimeInterval")
    is_auto_switch_enabled = obs.obs_data_get_bool(settings, "is_auto_switch_enabled")

def script_unload():
    """脚本卸载时调用"""
    pass

def script_save(settings):
    """保存脚本配置"""
    obs.obs_data_set_double(settings, "TimeInterval", TimeInterval)
    obs.obs_data_set_bool(settings, "is_auto_switch_enabled", is_auto_switch_enabled)

def script_defaults(settings):
    """设置脚本的默认配置"""
    obs.obs_data_set_default_double(settings, "TimeInterval", 0.2)
    obs.obs_data_set_default_bool(settings, "is_auto_switch_enabled", True)

def script_update(settings):
    """更新脚本配置"""
    global TimeInterval, is_auto_switch_enabled
    TimeInterval = obs.obs_data_get_double(settings, "TimeInterval")
    is_auto_switch_enabled = obs.obs_data_get_bool(settings, "is_auto_switch_enabled")

def test(props, prop):
    """测试按钮的回调函数"""
    try:
        scene_name = "UnityScene"
        scene_source = obs.obs_get_source_by_name(scene_name)
        if scene_source is not None:
            obs.script_log(obs.LOG_INFO, f"测试场景 '{scene_name}' 存在")
            obs.obs_source_release(scene_source)
        else:
            obs.script_log(obs.LOG_WARNING, f"测试场景 '{scene_name}' 不存在")
    except Exception as e:
        obs.script_log(obs.LOG_ERROR, f"测试时发生错误: {e}")


def start_recording(props, prop):
    """开始录制"""
    if not obs.obs_frontend_recording_active():
        obs.obs_frontend_recording_start()
        obs.script_log(obs.LOG_INFO, "录制已开始")
    else:
        obs.script_log(obs.LOG_WARNING, "录制已在进行中")

def stop_recording():
    """停止录制"""
    if obs.obs_frontend_recording_active():
        obs.obs_frontend_recording_stop()
        obs.script_log(obs.LOG_INFO, "录制已停止")
    else:
        obs.script_log(obs.LOG_WARNING, "当前未在录制")

def toggle_recording():
    """切换录制状态"""
    if obs.obs_frontend_recording_active():
        stop_recording()
    else:
        start_recording()